/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.showcase.server.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.cleangwt.showcase.server.entity.User;
import com.cleangwt.user.shared.Option;

/**
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
@Repository
public class UserDAO {

  private PersistenceManager pm;

  @Autowired
  public UserDAO(PersistenceManagerFactory t) {
    pm = t.getPersistenceManager();
  }

  public Long count(String id) {
    Query query = pm.newQuery(User.class);
    query.setResult("count(this)");
    return (Long) query.execute();
  }

  public void delete(User entity) {
    pm.deletePersistent(pm.getObjectById(User.class, entity.getId()));
  }

  @SuppressWarnings("unchecked")
  public List<Option> getUserOptions() {
    String query = "select name,id from " + User.class.getName();
    Query q = pm.newQuery(query);
    q.setResultClass(Option.class);
    List<Option> users = (List<Option>) q.execute();
    return users;
  }

  @SuppressWarnings("unchecked")
  public List<User> list(String id, List<String> orderBy, List<String> orderDir, int pageStart, int pageSize) {
    Query query = pm.newQuery(User.class);
    if (!StringUtils.isEmpty(id)) {
      query.setFilter("id == \"" + id + "\"");
    }
    if (orderBy != null && !orderDir.isEmpty()) {
      query.setOrdering(orderBy.get(0) + " " + orderDir.get(0));
    }
    query.setRange(pageStart, pageStart + pageSize);

    List<User> users = (List<User>) query.execute();
    return users;
  }

  public User read(Object id) {
    return (User) pm.getObjectById(User.class, id);
  }

  public void save(User user) {
    pm.makePersistent(user);
  }

}
